import json
import traceback
from hashlib import md5
import requests


class Iciba:
    def __init__(self, kw):
        self.kw = kw
        # 1准备起始url 和请求头信息
        self.url = "http://ifanyi.iciba.com/index.php"
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36',
            'Referer': 'http://www.iciba.com/',
            "Accept": "application/json, text/plain, */*",
        }
        self.params = {
            "c": "trans",
            "m": "fy",
            "client": "6",
            "auth_user": "key_ciba",
            "sign": self.get_sign(kw)[0:16],
        }
        self.data = {
            "from": "en",
            "to": "zh",
            "q": kw,
        }
        self.cookies = {
            "BAIDU_SSP_lcr": "https://www.baidu.com/link?url=t-0eA8AGGRWQ_MQpHfqZxHsXUH- Nd7Oyn9gzeXi96Cm&wd=&eqid=9246fdb50019001100000004625632be"
        }

    def get_sign(self, kw: str):
        # 返回sign
        str_or = "6key_cibaifanyicjbysdlove1" + kw.replace(r"(^\s*)|(\s*$)/", "")
        return md5(str_or.encode('utf-8')).hexdigest()

    def get_data(self):
        # 发送请求获取响应
        response = requests.post(self.url, headers=self.headers, params=self.params, data=self.data,cookies=self.cookies)
        print(response.url)
        return response.content.decode('utf-8')

    def parse_data(self, data):
        # print(data)
        try:
            data_dict = json.loads(data)
            out = data_dict["content"]["out"]
            print("原单词：{}----翻译后:{}".format(self.kw, out))
        except:
            traceback.print_exc()

    def save_data(self):
        pass

    def start(self):
        data = self.get_data()
        self.parse_data(data)
        self.save_data()


if __name__ == '__main__':
    d = Iciba(kw="my name is halon")
    d.start()
